<?php

namespace App\Recharge\Api;

use App\Jobs\SynChronousOrder;
use App\Models\InterfaceConfiguration;
use App\Models\Mysql\XnOrder;
use App\Models\Mysql\XnTerraceInfo;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use App\Recharge\Bean\RequestResultBean;
use Carbon\Carbon;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class lifeng extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $data = [
            'customerId'       => $bean->getSupplierNum(),
            'timestamp'         => time(),
            'productCode'        => $bean->getGoodsId(),
            'number'          => $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量
            'orderId'    => $bean->getOrderNo(),//订单号
            'money'         => (int)$bean->getUnitPrice(),
        ];
        $data['sign'] = $this -> sign($data,$bean->getSecretKey());
        return $data;
    }
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key){
        ksort($array);
        $data_url = urldecode(http_build_query($array));
        $md5_str  = $data_url.'&key='. $secret_key;
        $str      = md5($md5_str);
        return   strtoupper($str);
    }
    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        return $this->httpClient($http)->asJson()->post($config->recharge_url, $this->rechargeData($bean));

    }

    public function synchronous_processing(InterfaceConfiguration $config, BasicInformation $dataBean, RequestResultBean $bean): RequestResultBean
    {
        // 第三方接口返回的错误信息
        $errMessage = "";
        // 请求返回信息转数组
        $resp = json2array($bean->getResponse());
        $bean->setFormatResponse($resp);
        // 解析json 解析失败的话 就默认成功
        $result = data_get($resp, 'code') == 1;
        if (!$result) {
            $errMessage = data_get($resp, 'msg', $config->title . '下单失败');
        }
        // 判断并返回
        return $bean->setResult($result)
            ->setErrorMessage($errMessage)
            ->setApiSynchronousEndProcessing(function() use ($result, $resp, $dataBean) {
                $data = [
                    'code'=>$resp['code'],
                    'order_sn'=>$dataBean->getOrderNo(),
                    'msg'=>$resp['msg'],
                ];
                if ($resp['code'] == 1){
                    $data['cami']=$resp['data']['cards'][0];
                }
                SynChronousOrder::dispatch($dataBean->getNotifyUrl(),$data)->delay(Carbon::now())->onConnection('redis')->onQueue('sync_order');
            });
    }

    /**
     * @inheritDoc
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('code', '');
        $order_sn = $request->input('order_sn', '');
        $cami =$request->input('cami', '');
        if ($status == 1){
            if (empty($cami['cardno'])){
                return $this->apiNotifyData($order_sn, $status)
                        ->setExecute(true)
                        ->setRechargeSuccess($status == 1)
                        ->setCami('订单成功但是没有返回卡号');
            }
            $user_data = json_decode(XnTerraceInfo::query()->where('sid',20)->value('datas'),true);
            if (empty($user_data['iv'])){
                return $this->apiNotifyData($order_sn, $status)
                    ->setExecute(true)
                    ->setRechargeSuccess($status == 1)
                    ->setCami('第三方密钥不存在,解密失敗');
            }
            $cami = $this->decode_cami($cami,$user_data['iv']);
        }
        return $this->apiNotifyData($order_sn, $status)
            ->setExecute(in_array($status, [1,-1]))
            ->setRechargeSuccess($status == 1)
            ->setCami($cami)
            ->setRechargeErrorMessage($request->input('msg', ''));

    }

    /**
     * @param $cami
     * @param $key
     * @return string
     */
    public function decode_cami($cami,$key):string
    {
        $key = substr($key, 0, 16);
        $cardno  = openssl_decrypt(hex2bin($cami['cardno']), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        $cami =  openssl_decrypt(hex2bin($cami['cardkey']), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        $cami_arr = ['sku_one'=>$cardno, 'sku_two'=>$cami, 'sku_three'=>'',];
        return json_encode($cami_arr);
    }
}
